# coding=utf-8
# https://www.youtube.com/playlist?list=PLeHvwXyqearWT_NT7CiGm_kEiKabWNPKw
# 使用方法：在页面上全选，另存为输入文件。

import os
import re
import shutil
from pathlib import WindowsPath

BEG_FLAG = "全部播放  分享  保存"
END_FLAG = "语言： 中文   国家/地区： (.*)   受限模式： (.*)  历史记录  帮助"

def IsBegin(s):
	return BEG_FLAG == s

def IsEnd(s):
	m = re.search(END_FLAG, s)
	return True if m else False

def GetVideoListFromFile(filename):
    lst = []
    mode = 0
    line = 0
    with open(filename, encoding='utf-8') as f:
        rw = f.readline()
        line += 1
        while rw != "":
            rw = rw.strip()

            if mode == 0:
                if IsBegin(rw.strip()):
                    f.readline()
                    line += 1
                    mode = 1
            
            elif mode == 1:
                if IsEnd(rw):
                    mode = 2
                    break
                c2 = f.readline().strip() # Video title
                c3 = f.readline()
                c4 = f.readline().strip() # Video time <hh:mm:ss>
                line += 3

                lst.append((c2, c4)) # (video_title, video_time)

            rw = f.readline()
            line += 1

    if mode != 2:
        raise Exception("input error: " + str(line))
    
    return lst


def DestFileName(i, name, time, suffix = ".mp4"):
    return ("000" + str(i))[-3:] + " " + name + " (" + time.replace(":", "-") + ")" + suffix


def NormalFileName(name, suffix = ".mp4"):
    return name.replace(':', '_') + suffix


def CheckSourceFile(dir, name):
    fullname = os.path.join(dir, name)
    if not WindowsPath(fullname).is_file():
        print(fullname + "不存在。")
        return False
    return True


def CopyFile(srcpath, dstpath):
    if not WindowsPath(dstpath).exists():
        shutil.copy(srcpath, dstpath)


def CheckAndCopyFiles(SRC_PATH, DST_PATH, lst):
    for i, r in enumerate(lst, 1):
        new_name = NormalFileName(r[0])
        if CheckSourceFile(SRC_PATH, new_name):
            CopyFile(os.path.join(SRC_PATH, new_name), os.path.join(DST_PATH, DestFileName(i, new_name, r[1])))


if __name__ == "__main__":
#    print(GetVideoListFromFile("txt_list1.txt"))
#    print(GetVideoListFromFile("txt_list2.txt"))
    print(GetVideoListFromFile("txt_list5.txt"))
